package com.sf.fy.uav.applet.utils.exception;

import com.sf.fy.uav.common.exception.BusinessException;
import com.sf.fy.uav.common.utils.FloResponseModel;
import com.sf.fy.uav.common.utils.Rs;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;

/**
 * @author LTQ
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {
    private final static Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ResponseBody
    @ExceptionHandler(RuntimeException.class)
    public Rs globalException(HttpServletResponse response, RuntimeException ex) {
        log.info("GlobalExceptionHandler...");
        log.info("错误代码：" + response.getStatus());
        String msg;
        if (ObjectUtils.isEmpty(ex.getCause())) {
            msg = ex.getMessage();
            log.info(ex.getMessage());
        } else {
            msg = ex.getCause().getMessage();
            log.info(ex.getCause().getMessage());
        }
        return Rs.failed(msg);
    }

    @org.springframework.web.bind.annotation.ExceptionHandler(value = BusinessException.class)
    public ResponseEntity<FloResponseModel<String>> businessException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BusinessException e) throws IOException {
        httpServletResponse.setStatus(HttpStatus.OK.value());
        FloResponseModel floResponseModel = new FloResponseModel();
        floResponseModel.setSuccess(false);
        floResponseModel.setCode(e.getError().getErrCode());
        floResponseModel.setMsg(e.getMessage());
        HttpStatus httpStatus = HttpStatus.OK;
        if (httpServletRequest.getRequestURI().contains("feign")) {
            httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;
        }
        logger.error(String.format("访问 %s->业务异常！原因是:", httpServletRequest.getRequestURI()), e);
        return new ResponseEntity<>(floResponseModel, httpStatus);
    }
}
